<template>
  <div>
    <Category :scene="scene"></Category>
    <el-card shadow="hover" style="margin-top: 20px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!useCategoryStore.category3Id"
          @click="addAttr"
          v-hidden="'btn.Attr.add'"
          >添加属性</el-button
        >
        <el-table :data="attrList" border stripe style="margin: 20px 0">
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          />
          <el-table-column prop="attrName" label="属性名称" width="160px" />
          <el-table-column label="属性值列表">
            <template #="{ row, $index }">
              <el-tag
                :type="attrValue.id % 2 == 0 ? 'success' : ''"
                v-for="(attrValue, index) in row.attrValueList"
                :key="attrValue.id"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160px">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="updateAttr(row)"
                v-hidden="'btn.Attr.update'"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="deleteAttr(row)"
                v-hidden="'btn.Attr.remove'"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form inline>
          <el-form-item label="属性名">
            <el-input
              type="text"
              placeholder="请输入属性名字"
              v-model="attrParams.attrName"
            />
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!attrParams.attrName"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button @click="cancelHandler">取消</el-button>
        <el-table
          border
          stripe
          style="margin: 20px 0"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          />
          <el-table-column prop="name" label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                v-if="row.flag"
                type="text"
                size="small"
                v-model="row.valueName"
                @blur="toLook(row, $index)"
                :ref="(el) => (inputRef[$index] = el)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                @click="deleteAttrValue($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          :disabled="!attrParams.attrValueList.length"
          @click="saveAttr"
          >保存</el-button
        >
        <el-button @click="cancelHandler">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onUnmounted } from "vue";
import { Plus, Delete, Edit } from "@element-plus/icons-vue"; // 引入icon图标
import { cloneDeep } from "lodash";

import categoryStore from "@/stores/category"; // 引入store仓库
import {
  reqAttrList,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from "@/api/product/Attr"; // 请求函数
import type { IAttrList, IAttr, IAttrValue } from "@/api/product/Attr/model"; // 数据类型
import { ElMessage } from "element-plus";

const useCategoryStore = categoryStore(); // store仓库对象
const attrList = ref<IAttrList>([]); // 品牌属性及属性值数据
const scene = ref<number>(0); // 场景切换
const inputRef = ref<any>([]); // input标签实例集合

// 添加属性及属性值需要的参数
const attrParams = reactive<IAttr>({
  attrName: "",
  attrValueList: [],
  categoryId: "",
  categoryLevel: 3,
});

// 获取品牌属性及属性值的数据
const getAttrList = async () => {
  const result = await reqAttrList(
    useCategoryStore.category1Id,
    useCategoryStore.category2Id,
    useCategoryStore.category3Id
  );
  attrList.value = result;
};

// 监听三级分类id的变化， 获取品牌属性的数据
watch(
  () => useCategoryStore.category3Id,
  () => {
    if (useCategoryStore.category3Id) {
      getAttrList();
    }
  }
);

// 添加属性按钮的回调
const addAttr = () => {
  scene.value = 1;

  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    categoryId: useCategoryStore.category3Id,
    categoryLevel: 3,
    id: undefined,
  });
};

// 添加属性值按钮的回调
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    flag: true,
  });

  nextTick(() => {
    inputRef.value[attrParams.attrValueList.length - 1].focus();
  });
};

// 取消按钮的回调
const cancelHandler = () => {
  scene.value = 0;
};

// input框失去焦点切换查看模式
const toLook = (row: IAttrValue, index: number) => {
  if (!row.valueName) {
    ElMessage({
      type: "warning",
      message: "属性值必须填写",
      showClose: true,
      duration: 500,
    });

    attrParams.attrValueList.splice(index, 1);
  }

  const result = attrParams.attrValueList.find((item) => {
    if (row != item) {
      return row.valueName == item.valueName;
    }
  });

  if (result) {
    ElMessage({
      type: "warning",
      message: "属性值已存在",
      showClose: true,
      duration: 500,
    });

    attrParams.attrValueList.splice(index, 1);
  }

  row.flag = false;
};

// 点击div切换编辑模式
const toEdit = (row: IAttrValue, index: number) => {
  row.flag = true;

  nextTick(() => {
    inputRef.value[index].focus();
  });
};

// 添加或修改保存按钮的回调
const saveAttr = async () => {
  attrParams.attrValueList.forEach((item) => {
    if (item.hasOwnProperty("flag")) {
      delete item.flag;
    }
  });

  try {
    await reqAddOrUpdateAttr(attrParams);
    scene.value = 0;
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
      showClose: true,
    });

    getAttrList();
  } catch (error) {
    ElMessage({
      type: "warning",
      message: attrParams.id ? "修改失败" : "添加失败",
      showClose: true,
    });
  }
};

// 修改属性按钮的回调
const updateAttr = (row: IAttr) => {
  scene.value = 1;
  Object.assign(attrParams, cloneDeep(row));
};

// 删除属性按钮的回调
const deleteAttr = async (row: IAttr) => {
  try {
    await reqDeleteAttr(row.id);
    ElMessage({
      type: "success",
      message: "删除成功",
      showClose: true,
      duration: 500,
    });

    getAttrList();
  } catch (error) {
    ElMessage({
      type: "warning",
      message: "删除失败",
      showClose: true,
      duration: 500,
    });
  }
};

// 删除属性值按钮的回调
const deleteAttrValue = (index: number) => {
  attrParams.attrValueList.splice(index, 1);
};

onUnmounted(() => {
  useCategoryStore.clearCategory();
});
</script>

<style></style>
